package com.hmall.search.listen;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.hmall.api.client.ItemClient;
import com.hmall.api.dto.ItemDTO;
import com.hmall.search.domain.dto.ItemDoc;
import lombok.RequiredArgsConstructor;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
@RequiredArgsConstructor
public class ItemInfoListener {
    private final ItemClient itemClient;
    private RestHighLevelClient client = new RestHighLevelClient(
            RestClient.builder(HttpHost.create("http://192.168.64.128:9200")));


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "item.search.save.queue",durable = "true"),
            exchange = @Exchange(value = "item.search.direct"),
            key = {"save"}))
    public void listenItemSave(Long id) throws IOException {
        ItemDTO item = itemClient.queryItemById(id);
        ItemDoc itemDoc = BeanUtil.copyProperties(item, ItemDoc.class);
        IndexRequest request = new IndexRequest("items").id(itemDoc.getId());
        request.source(JSONUtil.toJsonStr(itemDoc), XContentType.JSON);
        client.index(request, RequestOptions.DEFAULT);
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "item.search.delete.queue",durable = "true"),
            exchange = @Exchange(value = "item.search.direct"),
            key = {"delete"}
    ))
    public void listenItemDelete(Long id) throws IOException {
            DeleteRequest request = new DeleteRequest("items", id.toString());
            client.delete(request,RequestOptions.DEFAULT);
    }
}
